package chat.components;


import javax.swing.JFrame;

import network.ChannelData;
import network.enums.ServerPackets;

import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.ListSelectionModel;
import javax.swing.border.LineBorder;
import java.awt.Color;
import java.awt.Dialog.ModalExclusionType;
import java.awt.Window.Type;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.UnsupportedEncodingException;

import javax.swing.JButton;

import app.AppGlobals;

public class ChannelWindow {
	
	public JFrame frame;
	public DefaultListModel<ChannelData> channelListModel;
	
	public ChannelWindow(ChannelData[] channels){
		initialize();
		setChannels(channels);
	}
	private void initialize() {
		frame = new JFrame();
		frame.setTitle("Channel Select");
		frame.setBounds(100, 100, 304, 370);
		frame.setModalExclusionType(ModalExclusionType.TOOLKIT_EXCLUDE);
		frame.setType(Type.UTILITY);
		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		frame.getContentPane().setLayout(null);
		
		channelListModel = new DefaultListModel<ChannelData>();
		final JList<ChannelData> channelList = new JList<ChannelData>(channelListModel);
		channelList.setBorder(new LineBorder(new Color(0, 0, 0)));
		channelList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		channelList.setDoubleBuffered(true);
		channelList.setCellRenderer(new ChannelCellRenderer());
		channelList.setBounds(10, 11, 271, 281);
		frame.getContentPane().add(channelList);
		
		JButton cancelBtn = new JButton("Cancel");
		cancelBtn.setBounds(192, 303, 89, 23);
		frame.getContentPane().add(cancelBtn);
		cancelBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				frame.dispose();
			}
		});
		
		JButton joinBtn = new JButton("Join");
		joinBtn.setBounds(102, 303, 89, 23);
		frame.getContentPane().add(joinBtn);
		joinBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				//if(channelListModel.in)
				if(channelList.getSelectedValue() != null){
					try {
						ChannelData channel = channelList.getSelectedValue();
						AppGlobals.gameServer.sendPacket(ServerPackets.JoinChannel, channel.name.getBytes("UTF-8"));
						frame.dispose();
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
			}
		});
		
		JButton createBtn = new JButton("Create");
		createBtn.setBounds(10, 303, 89, 23);
		frame.getContentPane().add(createBtn);
		createBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				
			}
		});
	}
	
	void setChannels(ChannelData[] channels){
		for (int i = 0; i < channels.length; i++)
			channelListModel.addElement(channels[i]);
	}
	

}
